import { Component, OnInit, TemplateRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { DictDto } from 'src/app/models/sys/dict.dto';
import { GroupDto } from 'src/app/models/sys/group.dto';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { ApiService } from 'src/app/services/api.service';
import { BehaviorSubject } from 'rxjs';
import { EditMode } from 'src/app/models/enums/edit-mode.enum';
import { GroupQueryParam } from 'src/app/models/param/group-query.param';
import { Consts } from 'src/app/consts/consts';
import { PageParam } from 'src/app/models/param/page.param';

const GROUP_NAME = 'groupName';
const GROUP_TYPE_ID = 'groupTypeId';
const REMARK = 'remark';
const GROUP_CODE = 'groupCode';

@Component({
  selector: 'app-group-info',
  templateUrl: './group-info.component.html',
  styleUrl: './group-info.component.less'
})
export class GroupInfoComponent implements OnInit {
  // Search fields
  searchForm!: UntypedFormGroup;
  pageIndex = 1;
  pageSize = 15;
  total = 0;
  submitted = false;

  groups: GroupDto[] = [];

  groupTypes: DictDto[] = [];
  selectedGroupType?: string;

  // 对话框title
  editTitle?: string;
  groupName?: string;

  // 详情
  groupSubject = new BehaviorSubject<GroupDto>(new GroupDto());

  // Modal
  modeSubject = new BehaviorSubject<{ mode: EditMode, group?: GroupDto }>({ mode: EditMode.ADD, group: undefined });

  constructor(private _api: ApiService,
    private _fb: UntypedFormBuilder,
    private _modal: NzModalService,
    private _message: NzMessageService) {
  }

  ngOnInit(): void {
    this.createSearchForm();
    this.onSearch();
    this.getGroupTypes();
  }

  createSearchForm() {
    this.searchForm = this._fb.group({});
    this.searchForm.addControl(GROUP_TYPE_ID, new UntypedFormControl('', [Validators.maxLength(20)]));
    this.searchForm.addControl(GROUP_NAME, new UntypedFormControl('', [Validators.maxLength(20)]));
    this.searchForm.addControl(REMARK, new UntypedFormControl('', [Validators.maxLength(20)]));
    this.searchForm.addControl(GROUP_CODE, new UntypedFormControl('', [Validators.maxLength(64)]));
  }

  onSearch() {
    const param = new GroupQueryParam();
    param.groupName = this.searchForm.get(GROUP_NAME)?.value;
    param.groupTypeId = this.searchForm.get(GROUP_TYPE_ID)?.value;
    param.remark = this.searchForm.get(REMARK)?.value;
    param.groupCode = this.searchForm.get(GROUP_CODE)?.value;
    param.pageNum = this.pageIndex;
    param.pageSize = this.pageSize;

    this._api.getGroupList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.groups = resp.data;
        this.total = resp.total;
      }
    });
  }

  getGroupTypes() {
    const param = new PageParam();
    param.pageNum = 1;
    param.pageSize = 10000;

    this._api.getGroupTypeList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.groupTypes = resp.data;
      }
    });
  }

  get fm() {
    return this.searchForm.controls;
  }

  onReset() { }

  onCreate(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>) {
    this.editTitle = '创建组';
    this.groupName = undefined;

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('group added');
      }
    });

    this.modeSubject.next({ mode: EditMode.ADD, group: undefined });
  }

  onUpdate(group: GroupDto, tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>) {
    this.editTitle = '编辑组';
    this.groupName = group.groupName;

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('group added');
      }
    });

    this.modeSubject.next({ mode: EditMode.EDIT, group: group });
  }

  onDetail(tplTitle: TemplateRef<object>, tplContent: TemplateRef<object>, group: GroupDto) {
    this.editTitle = '组详情';

    this._modal.create({
      nzTitle: tplTitle,
      nzContent: tplContent,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: false,
      nzWidth: 800,
      nzOnOk: () => {
        console.log('groupType detail');
      }
    });

    this.groupSubject.next(group);
  }

  handleDelete(groupId: number) {
    this._api.deleteGroup(groupId).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("删除组成功");
        this.onSearch();
      } else {
        this._message.warning("删除组失败 " + resp.message);
      }
    });
  }

  onPageParamChange(params: NzTableQueryParams) {
    this.pageIndex = params.pageIndex;
    this.pageSize = params.pageSize;
    this.onSearch();
  }

  onAddGroupEvent(result: boolean) {
    if (result) {
      this.onSearch();
    }

    this._modal.closeAll();
  }

  onDetailEvent(result: boolean) {
    this._modal.closeAll();
    console.log(`${result}`);
  }
}
